package com.itestor.iptv.modules.ne.actions;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;

import com.itestor.iptv.global.actions.AbstractOFCDataAction;
import com.itestor.iptv.global.bean.OFCGraph;
import com.itestor.iptv.modules.ne.service.IptvLostRateService;
import com.itestor.iptv.modules.ne.vo.IptvLostRateBean;
import com.itestor.iptv.modules.ne.vo.PictureData;

/**
 * 绘图:丢包率
 * @author masaki
 */
public class LossyOFCDataAction extends AbstractOFCDataAction {

    private Logger logger = Logger.getLogger(LossyOFCDataAction.class);

    /**
     * iptvLostRateService
     */
    private IptvLostRateService iptvLostRateService;
    private Integer maxNum = 1;
    /**
     * 日期输入格式.
     */
    private final DateFormat DATE_FAMAT = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm", Locale.UK);

    private final DateFormat INPUT_FAMAT = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss", Locale.UK);

    public LossyOFCDataAction() {
        super(null);
    }

    /**
     * @param iptvLostRateService
     */
    public void setIptvLostRateService(IptvLostRateService iptvLostRateService) {
        this.iptvLostRateService = iptvLostRateService;
    }

    @Override
    public OFCGraph buildData(ActionForm form, HttpServletRequest request) {
        Map<String, List<String>> returnMap = new HashMap<String, List<String>>();
        Map<String, List<String>> returnDateMap = new HashMap<String, List<String>>();
        List<String> randomColorList = new ArrayList<String>();
        List<Object[]> returnList = new ArrayList<Object[]>();

        List<IptvLostRateBean> lostRateBeanList = new ArrayList<IptvLostRateBean>();

        logger.info("ids param  :  " + request.getParameter("ids"));

        // String[] p1 = request.getParameter("pa").split("_!_");
        // Map<String, String> valueMap = new HashMap<String, String>();
        // for (String str : p1) {
        // valueMap.put(str.split("@")[0], str.split("@")[1]);
        // }
        //        
        // String time = valueMap.get("date");

        String time = request.getParameter("time");
        String[] p_ids = request.getParameter("ids").split("_");
        Integer statunitsec = 900;

        // Long startTime = 0L;
        // Long endTime = System.currentTimeMillis() / 1000L;
        if ("15min".equals(time)) {
            // startTime = (System.currentTimeMillis() - 15L * 60L * 1000L) /
            // 1000L;
            // endTime = System.currentTimeMillis() / 1000L;
            statunitsec = 900;
        }
        if ("30min".equals(time)) {
            // startTime = (System.currentTimeMillis() - 30L * 60L * 1000L) /
            // 1000L;
            // endTime = System.currentTimeMillis() / 1000L;
            statunitsec = 1800;
        }
        if ("2hour".equals(time)) {
            // startTime = (System.currentTimeMillis() - 2L * 60L * 60L * 1000L)
            // / 1000L;
            // endTime = System.currentTimeMillis() / 1000L;
            statunitsec = 7200;
        }

        //        
        // if (null != time && time.contains("startTime")) {
        // Map<String, String> tempMap = new HashMap<String, String>();
        // for (String str : time.split("_T_")) {
        // if (str.split("!").length > 1) {
        // tempMap.put(str.split("!")[0], str.split("!")[1]);
        // }
        // }
        // String sTime = tempMap.get("startTime");
        // String eTime = tempMap.get("endTime");
        // if (null != sTime && !"".equals(sTime)) {
        // try {
        // startTime = DATE_FAMAT.parse(sTime).getTime() / 1000L;
        // } catch (ParseException e) {
        // e.printStackTrace();
        // }
        // }
        // if (null != eTime && !"".equals(eTime)) {
        // try {
        // endTime = DATE_FAMAT.parse(eTime).getTime() / 1000L;
        // } catch (ParseException e) {
        // e.printStackTrace();
        // }
        // }
        // }

        String start_time = request.getParameter("startTime");
        String end_time = request.getParameter("endTime");

        Calendar start_Calendar = Calendar.getInstance();
//        start_Calendar.set(Calendar.DAY_OF_MONTH, start_Calendar
//                .get(Calendar.DAY_OF_MONTH - 1));

        start_Calendar.set(Calendar.HOUR_OF_DAY, start_Calendar.get(Calendar.HOUR_OF_DAY) - 48);        
        Date start = start_Calendar.getTime();
        
        Calendar end_Calendar = Calendar.getInstance();
        Date end = end_Calendar.getTime();

        if (!StringUtils.isEmpty(start_time)) {
            try {
                start = DATE_FAMAT.parse(start_time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (!StringUtils.isEmpty(end_time)) {
            try {
                end = DATE_FAMAT.parse(end_time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        logger.info("startTime : " + start_time + "endTime:" + end_time);

        String[] pvids = p_ids;
        // String[] pvids = valueMap.get("id").split("_");
        if (null != pvids && pvids.length > 0) {

            Integer[] ids = new Integer[pvids.length];
            for (int i = 0; i < pvids.length; i++) {
                try {
                    System.out.println(pvids[i]);
                    ids[i] = Integer.parseInt(pvids[i]);
                } catch (NumberFormatException e) {
                    ids[i] = 0;
                }
            }
            // logger.info("startTime = "
            // + DATE_FAMAT.format(new Date(startTime * 1000L)));
            // logger.info("endTime = "
            // + DATE_FAMAT.format(new Date(endTime * 1000L)));

            logger.info("ids [" + ids + "]");

            // returnList = iptvLostRateService.getIptvLostRateByIdsAndTime(ids,
            // startTime, endTime);

            // Date start=INPUT_FAMAT.parse("2010-11-01 00:00:00");
            // Date end=INPUT_FAMAT.parse("2010-11-02 23:59:59");

            lostRateBeanList = iptvLostRateService
                    .getIptvLostRateBeanByIdsAndTime(ids,
                            start.getTime() / 1000, end.getTime() / 1000,
                            statunitsec);

            logger.info("lostRateBeanList size  : " + lostRateBeanList.size());

        }

        // for (Object[] iptvLostRate : returnList) {
        // String rate = getRate((Long) iptvLostRate[2],
        // (Long) iptvLostRate[3]);
        // String date = getDate((Long) iptvLostRate[4]);
        // if (returnMap.containsKey(iptvLostRate[0] + "_" + iptvLostRate[1])) {
        // returnMap.get(iptvLostRate[0] + "_" + iptvLostRate[1])
        // .add(rate);
        // returnDateMap.get(iptvLostRate[0] + "_" + iptvLostRate[1]).add(
        // date);
        // } else {
        // List<String> tempList = new ArrayList<String>();
        // List<String> tempDateList = new ArrayList<String>();
        // tempList.add(rate);
        // tempDateList.add(date);
        // returnMap
        // .put(iptvLostRate[0] + "_" + iptvLostRate[1], tempList);
        // returnDateMap.put(iptvLostRate[0] + "_" + iptvLostRate[1],
        // tempDateList);
        // }
        // }

        for (IptvLostRateBean iptvLostRate : lostRateBeanList) {

            for (PictureData data : iptvLostRate.getDataList()) {

                String date = getDate(data.getTime());
                if (returnMap.containsKey(iptvLostRate.getIdRobot() + "_"
                        + iptvLostRate.getName())) {
                    returnMap.get(
                            iptvLostRate.getIdRobot() + "_"
                                    + iptvLostRate.getName()).add(
                            getRate(data.getRate()));
                    returnDateMap.get(
                            iptvLostRate.getIdRobot() + "_"
                                    + iptvLostRate.getName()).add(date);
                } else {
                    List<String> tempList = new ArrayList<String>();
                    List<String> tempDateList = new ArrayList<String>();
                    tempList.add(String.valueOf(data.getRate()));
                    tempDateList.add(date);
                    returnMap.put(iptvLostRate.getIdRobot() + "_"
                            + iptvLostRate.getName(), tempList);

                    returnDateMap.put(iptvLostRate.getIdRobot() + "_"
                            + iptvLostRate.getName(), tempDateList);
                }

            }

        }

        OFCGraph graphData = new OFCGraph();
        String tempKey = "";
        // 循环输出多条曲线
        for (String key : returnMap.keySet()) {
            tempKey = key;
            graphData.set_data(returnMap.get(key));
            String color = randomColor();
            if (randomColorList.size() > 0) {
                while (randomColorList.contains(color)) {
                    color = randomColor();
                }
            }
            graphData.area_hollow("2", "0", "25", color,
                    key.split("_").length > 1 ? key.split("_")[1] : "", "12",
                    color);
        }
        graphData.set_x_labels(returnDateMap.get(tempKey));
        int xSteps = returnDateMap.get(tempKey).size() / 24;
        graphData.set_x_offset(false);
        graphData.set_y_max(this.maxNum);
        graphData.set_y_min(0);

        graphData.set_x_axis_steps(xSteps);
        graphData.set_x_label_style("10", "#000000", 0, xSteps * 5, "");

        graphData.set_y_legend("%", 13, "#C11B01");
        return graphData;
    }

    /**
     * 计算出比例，显示Y坐标用
     * @param errorCount
     * @param tatolCount
     * @return
     */
    public String getRate(Long errorCount, Long tatolCount) {
        Double rate = errorCount.doubleValue() / tatolCount.doubleValue()
                * 100.0;
        if (rate > this.maxNum) {
            this.maxNum = rate.intValue() + 1;
        }
        return "" + rate;
    }

    /**
     * 计算出比例，显示Y坐标用
     * @param dataVal
     * @return String
     */
    public String getRate(Double dataVal) {
        if (dataVal > this.maxNum) {
            this.maxNum = (100 - dataVal.intValue()) + 1;
        }
        return "" + 0;
    }

    /**
     * 将Long类型转换成Date类，显示x坐标用
     * @param logTime
     * @return
     */
    public String getDate(Long logTime) {
        return DATE_FAMAT.format(new Date(logTime * 1000L));
    }

    /**
     * 将Long类型转换成Date类，显示x坐标用
     * @param logTime
     * @return
     */
    public String getDate(String logTime) {
        Date time = null;
        try {
            time = INPUT_FAMAT.parse(logTime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (null != time) {
            return DATE_FAMAT.format(time);
        } else {
            return "";
        }
    }

    /**
     * 随机色
     * @return color
     */
    public String randomColor() {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        sb.append("#");
        for (int i = 0; i < 6; i++) {
            int temp = random.nextInt(16);
            if (temp >= 10) {
                switch (temp) {
                case 10:
                    sb.append("A");
                    break;
                case 11:
                    sb.append("B");
                    break;
                case 12:
                    sb.append("C");
                    break;
                case 13:
                    sb.append("D");
                    break;
                case 14:
                    sb.append("E");
                    break;
                default:
                    sb.append("F");
                    break;
                }
            } else {
                sb.append(temp);
            }
        }
        return sb.toString();
    }

    // public static void main(String[] args) {
    // DateFormat DATE_FAMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm",
    // Locale.UK);
    // System.out.println(DATE_FAMAT.format(new Date(1285409700L*1000L)));
    // }
}
